package com.itboye.lottery.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.itboye.lottery.R;
import com.itboye.lottery.adapter.BonusOptimizationAdapter;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.base.BaseActivity;
import com.itboye.lottery.bean.OrderBean;
import com.itboye.lottery.bean.ZqBetListItem;
import com.itboye.lottery.bean.ZqMatchDataCheck;
import com.itboye.lottery.callback.PayCallBack;
import com.itboye.lottery.dialog.PayDialog;
import com.itboye.lottery.enums.LotteryType;
import com.itboye.lottery.presenter.UserPresenter;
import com.itboye.lottery.retrofit.ResponseCallback;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

import butterknife.BindView;

import static com.itboye.lottery.utils.GsonUtil.getSkipIdAndGroupIdGson;

/**
 * Created by ZD on 2017/5/9.
 * 奖金优化
 */

public class BonusOptimizationActivity extends BaseActivity implements ResponseCallback {

    //    BonusOptimizationAdapter adapter;
    EditText include_multiple_context;
    RadioButton rb_pj;
    RadioButton rb_br;
    RadioButton rb_bl;
    RadioGroup rg_tab;
    RecyclerView lv_body;
    @BindView(R.id.llContainer)
//    LinearLayout llContainer;
//    @BindView(R.id.tv_bonus)
            TextView tv_bonus;
    TextView tv_bottom_sure;
    //过关玩法
    String num = "";
    String type = "avg";
    String free_pass;
    int multiple = 1;
    private String mPlayTypeNum;
    private LotteryType mLotteryMode;
    float totalMoney;
    TextView tv_bottom_1, tv_jiangjinyouhua, tv_biaozhunguoguan;
    ImageView iv_bottom_increase_multiple, iv_bottom_reduce_multiple;

//    private ShowOrderDialog mShowOrderDialog;

    HashMap<String, HashMap<String, String>> map = new LinkedHashMap<>();
    ArrayList<ZqBetListItem> zqBetListItemArrayList = new ArrayList<>();
    private BonusOptimizationAdapter adapter;

    UserPresenter userPresenter = new UserPresenter(this);
    private ArrayList<ZqMatchDataCheck.ListEntity> arrayList = new ArrayList<>();
    private String bonus = "";
    EditText tv_bottom_beishu_multiple;
    RelativeLayout rl_multiple;
    int voteNum;//注数
    TextView tv_bottom_total;
    LotteryType lotteryType;
    TextView tv_bottom_faqigendan;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bonus_optimization;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View view) {
        int position = 0;
        int tempMultiple = 0;
        switch (view.getId()) {
            case R.id.item_bonusopt_tv_team:
                position = (int) view.getTag();
                arrayList.get(position).setVisible(!arrayList.get(position).isVisible());
                adapter.notifyDataSetChanged();
                break;
            case R.id.tv_jian:
                position = (int) view.getTag();
                tempMultiple = arrayList.get(position).getMultiple();
                tempMultiple--;
                arrayList.get(position).setMultiple(tempMultiple);
                adapter.notifyDataSetChanged();
                break;
            case R.id.tv_jia:
                position = (int) view.getTag();
                tempMultiple = arrayList.get(position).getMultiple();
                tempMultiple++;
                arrayList.get(position).setMultiple(tempMultiple);
                adapter.notifyDataSetChanged();
                break;
            case R.id.tv_bottom_sure://投注
                String orignNum = num;
                String num = getSkipIdAndGroupIdGson().toJson(arrayList);
//                multiple = Integer.parseInt(tv_bottom_beishu_multiple.getText().toString());
                multiple = 1;
                if (lotteryType == LotteryType.JCZQ) {
                    userPresenter.zqCreateOrder(num, orignNum, multiple, free_pass);
                } else if (lotteryType == LotteryType.JCLQ) {
                    userPresenter.lqCreateOrder(num, orignNum, multiple, free_pass);
                }
                break;
            case R.id.iv_bottom_reduce_multiple://倍数减
                if (Integer.valueOf(tv_bottom_beishu_multiple.getText().toString()) > 1) {
                    tv_bottom_beishu_multiple.setText("" + (Integer.valueOf(tv_bottom_beishu_multiple.getText().toString()) - 1));
//                    setTotalMultibalAndBetZhuShuAndMoney();
                }
                break;
            case R.id.iv_bottom_increase_multiple://倍数加
                if (Integer.valueOf(tv_bottom_beishu_multiple.getText().toString()) < 100) {
                    tv_bottom_beishu_multiple.setText("" + (Integer.valueOf(tv_bottom_beishu_multiple.getText().toString()) + 1));
//                    setTotalMultibalAndBetZhuShuAndMoney();
                }
                break;
            case R.id.rb_pj:
                type = "avg";
                getData();
                break;
            case R.id.rb_br:
                type = "hot";
                getData();
                break;
            case R.id.rb_bl:
                type = "cold";
                getData();
                break;
            case R.id.et_multiple:
                position = (int) view.getTag();
                showInputDialog(position);
                break;
        }
    }

    @SuppressLint("SetTextI18n")
    private void showInputDialog(final int position) {
        ZqMatchDataCheck.ListEntity listEntity = arrayList.get(position);
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("输入倍数");
        View view = View.inflate(this, R.layout.alert_x, null);
        EditText editText = view.findViewById(R.id.edit_content);
        editText.setText(listEntity.getMultiple() + "");
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        editText.setHint("请输入倍数");
        alert.setView(view);
        alert.setPositiveButton("确认", (dialogInterface, i) -> {
            if (!TextUtils.isEmpty(editText.getText())) {
                arrayList.get(position).setMultiple(Integer.parseInt(editText.getText().toString()));
                adapter.notifyDataSetChanged();
            }

        });
        alert.setNegativeButton("取消", (dialogInterface, i) -> {

        });
        alert.create().show();
    }

    @Override
    public void initData() {
        lotteryType = (LotteryType) getIntent().getSerializableExtra("type");
        tv_bottom_faqigendan.setVisibility(lotteryType == LotteryType.JCZQ ? View.VISIBLE : View.GONE);
        totalMoney = getIntent().getFloatExtra("totalMoney", 0) + 2;
        voteNum = getIntent().getIntExtra("voteNum", 1);
        tv_bottom_total.setText(String.format("共%d注", voteNum));
        map = (HashMap<String, HashMap<String, String>>) getIntent().getSerializableExtra("map");
        zqBetListItemArrayList = (ArrayList<ZqBetListItem>) getIntent().getSerializableExtra("array");
        adapter = new BonusOptimizationAdapter(this, arrayList);
        lv_body.setLayoutManager(new LinearLayoutManager(this));
        lv_body.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        lv_body.setAdapter(adapter);
        num = getIntent().getStringExtra("num");
        free_pass = getIntent().getStringExtra("free_pass");
        if (free_pass.equals("单")) {
            free_pass = "1";
        }
        multiple = getIntent().getIntExtra("multiple", 1);
        mLotteryMode = (LotteryType) getIntent().getSerializableExtra("lottery_type");
        tv_bottom_beishu_multiple.setText(multiple + "");
        tv_bottom_1.setVisibility(View.GONE);
        tv_jiangjinyouhua.setVisibility(View.GONE);
        tv_biaozhunguoguan.setVisibility(View.GONE);
        rl_multiple.setVisibility(View.GONE);
        getRequestParams();
//        money = getIntent().getIntExtra("money", 0);
//        term=getIntent().getStringExtra(PAY_TERM);
//        playtype=getIntent().getStringExtra(PAY_TYPE);
//        mPlayTypeNum = getIntent().getStringExtra(PAY_TYPE_NUM);
//        String mp = getIntent().getStringExtra(PAY_MULTIPLE);
//        Intent intent = getIntent();
//        multiple = TextUtils.isEmpty(mp) ? 1 : Integer.parseInt(mp);
//        tnum = String.valueOf(money / 2);
        optimizType();
        setTitle("奖金优化");
    }

    public void faQiGenDan(View view) {
        if (TextUtils.isEmpty(tv_bottom_beishu_multiple.toString())) {
            ByAlert.alert("请输入倍数");
            return;
        }
        multiple = Integer.parseInt(tv_bottom_beishu_multiple.getText().toString());
        if (multiple <= 0) {
            ByAlert.alert("倍数不能小于0");
            return;
        }
        //发起跟单
        startActivity(new Intent(this, FaQiGenDanActivity.class)
                .putExtra("hash", zqBetListItemArrayList)
                .putExtra("single_money", zqBetListItemArrayList)
                .putExtra("multiple", 1)
                .putExtra("passType", free_pass)
                .putExtra("lottery_type", mLotteryMode)
                .putExtra("pass_type", getIntent().getStringExtra("pass_type"))
                .putExtra("num", num)
                .putExtra("total_money", totalMoney));
    }

    private void getRequestParams() {
        if (lotteryType == LotteryType.JCZQ) {
            userPresenter.getFootBallMathDataCheck(num, multiple, free_pass);
        } else if (lotteryType == LotteryType.JCLQ) {
            userPresenter.getBasketballMathDataCheck(num, multiple, free_pass);
        }
    }

    //优化类型
    void optimizType() {
        include_multiple_context.setText(totalMoney + "");
        rg_tab.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_pj:
                    type = "avg";
                    break;
                case R.id.rb_br:
                    type = "hot";
                    break;
                case R.id.rb_bl:
                    type = "cold";
                    break;
            }
            getData();
        });
    }

    void getData() {
        showDialog();
        if (!TextUtils.isEmpty(include_multiple_context.getText().toString())) {
            totalMoney = Float.parseFloat(include_multiple_context.getText().toString());
        }
        userPresenter.optimize(type, totalMoney, bonus);//奖金辅助接口
    }


    @Override
    public void success(@NotNull Object o, @NotNull String requestSuccessType) {
        dissDialog();
        ArrayList<Float> bonusArray = new ArrayList<>();
        if (requestSuccessType == userPresenter.getFootBallMathDataCheck_SUCCESS) {
            ZqMatchDataCheck zqMatchDataCheck = (ZqMatchDataCheck) o;
            arrayList.clear();
            arrayList.addAll(zqMatchDataCheck.getList());
            //计算奖金注数等等
            //计算单倍金额
            for (int i = 0; i < arrayList.size(); i++) {
                arrayList.get(i).setSingleBonus(arrayList.get(i).getBonus() / arrayList.get(i).getMultiple());//单倍金额
                bonusArray.add((float) arrayList.get(i).getSingleBonus());
            }
            bonus = new Gson().toJson(bonusArray);
            //将对应的赛事信息补充到里面
            insertMatchInfoData();
            getData();
        }
        if (requestSuccessType == userPresenter.getBasketballMathDataCheck_SUCCESS) {
            ZqMatchDataCheck zqMatchDataCheck = (ZqMatchDataCheck) o;
            arrayList.clear();
            arrayList.addAll(zqMatchDataCheck.getList());
            //计算奖金注数等等
            //计算单倍金额
            for (int i = 0; i < arrayList.size(); i++) {
                arrayList.get(i).setSingleBonus(arrayList.get(i).getBonus() / arrayList.get(i).getMultiple());//单倍金额
                bonusArray.add((float) arrayList.get(i).getSingleBonus());
            }
            bonus = new Gson().toJson(bonusArray);
            //将对应的赛事信息补充到里面
//            insertBasketMatchInfoData();
            getData();
        } else if (requestSuccessType == userPresenter.optimize_SUCCESS) {
            ArrayList<ArrayList<String>> arrayListArrayList = (ArrayList<ArrayList<String>>) o;
            for (int i = 0; i < arrayList.size(); i++) {
                ZqMatchDataCheck.ListEntity listEntity = arrayList.get(i);
                for (ArrayList<String> strings : arrayListArrayList) {
                    float bonus = Float.parseFloat(strings.get(0));
                    if (bonus == listEntity.getBonus()) {
                        arrayList.get(i).setSingleBonus(bonus);
                        arrayList.get(i).setMultiple(Integer.parseInt(strings.get(1)));
                        break;
                    }
                }
            }
            adapter.notifyDataSetChanged();
        } else if (requestSuccessType == userPresenter.zqCreateOrder_SUCCESS || requestSuccessType == userPresenter.lqCreateOrder_SUCCESS) {
            OrderBean orderBean = (OrderBean) o;
            PayDialog payDialog = new PayDialog(this, true);
            payDialog.setOrderBean(orderBean);
            payDialog.setCallBack(new PayCallBack() {
                @Override
                public void paySuccess() {
                    finish();
                }

                @Override
                public void payFail(String msg) {

                }
            });
            payDialog.show();
        }
    }

    private void insertMatchInfoData() {
        for (int i = 0; i < arrayList.size(); i++) {
            ZqMatchDataCheck.ListEntity listEntity = arrayList.get(i);
            String[] content = listEntity.getContent().split("\\|");
            String[] desc = listEntity.get_desc().split(" ");
            String[] descChild = desc[1].split("x");
            descChild[0] = descChild[0].substring(5, descChild[0].length());
            for (int i1 = 0; i1 < content.length; i1++) {
                String s = content[i1];
                String[] contentChild = s.split("-");
                String desDateTime = descChild[i1].substring(0, descChild[i1].indexOf("("));
                if (desDateTime.equals(contentChild[0])) {
                    ZqBetListItem zqBetListItem = new ZqBetListItem();
                    String betContentChinese = descChild[i1].substring(descChild[i1].indexOf("(") + 1, descChild[i1].lastIndexOf(")"));
                    arrayList.get(i).getMatch_list().add(zqBetListItem);
                    for (ZqBetListItem zqBetListItem2 : zqBetListItemArrayList) {
                        String dateTime = zqBetListItem2.getbDate().replaceAll("-", "") + zqBetListItem2.getNum();
                        if (dateTime.equals(contentChild[0])) {
                            zqBetListItem.sethTeam(zqBetListItem2.gethTeam());
                            zqBetListItem.setaTeam(zqBetListItem2.getaTeam());
                            zqBetListItem.setNum(zqBetListItem2.getNum());
                            String passType = contentChild[1];//过关方式
                            String peilv = "";
                            switch (passType) {
                                case "3010"://胜平负
                                    for (ZqBetListItem.SpfBean spfBean : zqBetListItem2.getSpfList()) {
                                        if (betContentChinese.equals("负") && spfBean.getKey().equals("客胜")) {
                                            peilv = spfBean.getValue();
                                            break;
                                        }
                                        if (betContentChinese.equals("胜") && spfBean.getKey().equals("主胜")) {
                                            peilv = spfBean.getValue();
                                            break;
                                        } else if (spfBean.getKey().equals(betContentChinese)) {
                                            peilv = spfBean.getValue();
                                            break;
                                        }
                                    }
                                    zqBetListItem.setBetContent(betContentChinese + "[" + peilv + "]");
                                    break;
                                case "3006"://让球胜平负
                                    for (ZqBetListItem.SpfBean spfBean : zqBetListItem2.getRspfList()) {
                                        if (betContentChinese.equals("负") && spfBean.getKey().equals("客胜")) {
                                            peilv = spfBean.getValue();
                                            break;
                                        }
                                        if (betContentChinese.equals("胜") && spfBean.getKey().equals("主胜")) {
                                            peilv = spfBean.getValue();
                                            break;
                                        } else if (spfBean.getKey().equals(betContentChinese)) {
                                            peilv = spfBean.getValue();
                                            break;
                                        }
                                    }
                                    zqBetListItem.setBetContent("让" + betContentChinese + "[" + peilv + "]");
                                    break;
                                case "3007"://全场比分(90分钟)
                                    //胜4:2
                                    for (ZqBetListItem.SpfBean spfBean : zqBetListItem2.getBfList()) {
                                        if (spfBean.getKey().equals("平其它") && betContentChinese.contains("平9:9")) {
                                            peilv = spfBean.getValue();
                                            betContentChinese = spfBean.getKey();
                                            break;
                                        } else if (spfBean.getKey().equals("胜其它") && betContentChinese.contains("胜9:0")) {
                                            peilv = spfBean.getValue();
                                            betContentChinese = spfBean.getKey();
                                            break;
                                        } else if (spfBean.getKey().equals("负其它") && betContentChinese.contains("负0:9")) {
                                            peilv = spfBean.getValue();
                                            betContentChinese = spfBean.getKey();
                                            break;
                                        } else if (spfBean.getKey().equals(betContentChinese.substring(1, betContentChinese.length()))) {
                                            peilv = spfBean.getValue();
                                            break;
                                        }
                                    }
                                    zqBetListItem.setBetContent(betContentChinese + "[" + peilv + "]");
                                    break;
                                case "3008"://进球数
                                    for (ZqBetListItem.SpfBean spfBean : zqBetListItem2.getZjqList()) {
                                        if (spfBean.getKey().substring(0, spfBean.getKey().length() - 1).equals(betContentChinese)) {
                                            peilv = spfBean.getValue();
                                            break;
                                        }
                                    }
                                    zqBetListItem.setBetContent(betContentChinese + "[" + peilv + "]");
                                    break;
                                case "3009"://半全场胜负
                                    for (ZqBetListItem.SpfBean spfBean : zqBetListItem2.getBqcList()) {
                                        if (spfBean.getValue().equals(betContentChinese)) {
                                            peilv = spfBean.getKey();
                                            break;
                                        }
                                    }
                                    zqBetListItem.setBetContent(betContentChinese + "[" + peilv + "]");
                                    break;
                                case "3011":// 混合过关 （一注投注中包含2个玩法以上的就是混合过关）
                                    break;
                            }
                            break;
                        }

                    }
                }

            }
        }

    }

    @Override
    public void fail(int code, @NotNull Object msg, @NotNull String requestErrorType) {
        dissDialog();
        if (requestErrorType == userPresenter.getFootBallMathDataCheck_FAIL) {
            ByAlert.alert(msg);
        } else if (requestErrorType == userPresenter.optimize_FAIL) {
            ByAlert.alert(msg);
        } else if (requestErrorType == userPresenter.zqCreateOrder_FAIL) {
            ByAlert.alert(msg);
        }
    }
}
